package com.moyu.article.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.moyu.article.domain.board.vo.BoardQueryVO;
import com.moyu.article.domain.post.Post;
import com.moyu.article.domain.post.dto.*;
import com.moyu.article.domain.post.vo.PostListVO;
import com.moyu.article.domain.post.vo.PostQueryVO;
import com.moyu.article.domain.post.vo.PostVO;
import com.moyu.article.mapper.PostMapper;
import com.moyu.article.service.IPostService;
import com.moyu.common.core.contants.HttpConstants;
import com.moyu.common.core.domain.LoginUser;
import com.moyu.common.core.domain.R;
import com.moyu.common.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 赵彦博
 * @Date 2025/3/29 19:05
 */
@Service
public class PostServiceImpl implements IPostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public List<PostVO> getPostList(PostQueryDTO postQueryDTO) {
        PageHelper.startPage(postQueryDTO.getPageNum(), postQueryDTO.getPageSize());
        return postMapper.getPostList(postQueryDTO);
    }

    @Override
    public int updatePost(PostUpdateStateDTO postUpdateStateDTO) {
        return postMapper.updatePost(postUpdateStateDTO);
    }

    @Override
    public List<PostListVO> getListByNewest(PostQueryListDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return postMapper.getListByNewest(dto);
    }

    @Override
    public List<PostListVO> getListByHot(PostQueryListDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return postMapper.getListByHot(dto);
    }

    @Override
    public List<PostListVO> getListByUnanswered(PostQueryListDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return postMapper.getListByUnanswered(dto);
    }

    public int createPost(PostSaveDTO saveDTO) {
        Post post = new Post();
        post.setUserId(Long.valueOf(saveDTO.getUserId()));
        post.setVisitCount(0);
        post.setState(1);
        post.setTitle(saveDTO.getPostTitle());
        post.setContent(saveDTO.getPostContent());
        post.setCreateBy(Long.valueOf(saveDTO.getUserId()));
        post.setCreateTime(LocalDateTime.now());

        // 插入 post 数据
        int insert = postMapper.insert(post);

        // 获取生成的 post_id
        Long postId = post.getPostId();

        String boardVOS = saveDTO.getBoards();
        if (boardVOS != null && !boardVOS.isEmpty()) {
            // 准备批量插入的数据
            List<Map<String, Object>> batchList = new ArrayList<>();
            String[] split = boardVOS.split(",");
            for (int i = 0; i < split.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("boardId", split[i]);
                map.put("postId", postId);
                batchList.add(map);
            }
            // 批量插入 tb_board_post 表
            postMapper.batchInsertBoardPost(batchList);
        }
        return insert;
    }

    @Override
    public Boolean getIsLike(PostIsLikeDTO dto) {
        LoginUser loginUser = tokenService.getLoginUser(dto.getToken(), secret);
        String userId = loginUser.getUserId();
        return postMapper.getIsLike(dto.getPostId(), userId);
    }

    @Override
    public int insertLikeWithPost(PostIsLikeDTO dto) {
        LoginUser loginUser = tokenService.getLoginUser(dto.getToken(), secret);
        String userId = loginUser.getUserId();
        return postMapper.insertLikeWithPost(dto.getPostId(), userId);
    }

    @Override
    public int deleteLikeWithPost(PostIsLikeDTO dto) {
        LoginUser loginUser = tokenService.getLoginUser(dto.getToken(), secret);
        String userId = loginUser.getUserId();
        return postMapper.deleteLikeWithPost(dto.getPostId(), userId);
    }

    @Override
    public PostQueryVO getPostDetail(Long postId) {
        PostQueryVO post = postMapper.selectPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }

        // 更新访问量
        postMapper.updatePostVisitCount(postId);

        // 获取板块信息
        List<BoardQueryVO> boards = postMapper.selectBoardsByPostId(postId);
        post.setBoards(boards);

        return post;
    }

    @Override
    public void likePost(Long postId, Long userId) {
        if (postMapper.checkPostLikeStatus(postId, userId) > 0) {
            throw new RuntimeException("已经点赞过该帖子");
        }
        postMapper.insertLikeWithPost(String.valueOf(postId), String.valueOf(userId));
    }

    @Override
    public int deletePost(String postId) {
        return postMapper.deletePost(postId);
    }

    @Override
    public int updatePostByUser(PostUpdateDTO dto) {
        List<BoardQueryVO> boardQueryVOS = postMapper.selectBoardsByPostId(Long.valueOf(dto.getPostId()));
        List<String> boardIds = new ArrayList<>();
        for (int i = 0; i < boardQueryVOS.size(); i++) {
            BoardQueryVO boardQueryVO = boardQueryVOS.get(i);
            String boardId = boardQueryVO.getBoardId();
            boardIds.add(boardId);
        }
        List<Map<String, Object>> batchList = new ArrayList<>();
        if (dto.getBoardId() != null && !dto.getBoardId().isEmpty()) {
            for (int i = 0; i < dto.getBoardId().size(); i++) {
                String currentBoardId = dto.getBoardId().get(i);
                if (!boardIds.contains(currentBoardId)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("boardId", currentBoardId);
                    map.put("postId", dto.getPostId());
                    batchList.add(map);
                }
            }

            if (!batchList.isEmpty()) {
                postMapper.batchInsertBoardPost(batchList);
            }
        }
        return postMapper.updatePostByUser(dto);
    }

    @Override
    public Boolean checkFavoriteStatus(String token, String postId) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        String userId = loginUser.getUserId();
        return postMapper.checkFavoriteStatus(postId,userId);
    }

    @Override
    public int favoritePost(String token,String postId) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        String userId = loginUser.getUserId();
        return postMapper.favoritePost(postId,userId);
    }

    @Override
    public int cancelFavoritePost(String token,String postId) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        String userId = loginUser.getUserId();
        return postMapper.cancelFavoritePost(postId,userId);
    }

    @Override
    public void cancelLikePost(Long postId, Long userId) {
        if (postMapper.checkPostLikeStatus(postId, userId) == 0) {
            throw new RuntimeException("还未点赞过该帖子");
        }
        postMapper.deleteLikeWithPost(String.valueOf(postId), String.valueOf(userId));
    }

    @Override
    public boolean checkLikeStatus(Long postId, Long userId) {
        return postMapper.checkPostLikeStatus(postId, userId) > 0;
    }


}
